import { doLogin, doLogout } from "@/api/auth";
import { LoginResult, Token } from "@/api/auth/type";
import { router } from "@/router";
import { Store } from "@tauri-apps/plugin-store";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { User } from "@/api/user/type";

export const useAuthStore = defineStore('auth', () => {
    const isLogin = ref(false)
    const token = ref({} as Token)
    const getToken = computed(() => `${token.value.prefix} ${token.value.content}`)
    const getIsLogin = computed(() => isLogin.value)
    function login(username: string, password: string) {
        doLogin({
            username, password, rememberMe: false,
            captcha: {
                captchaBase64: '',
                captchaKey: '',
                captchaCode: ''
            }
        }).then(async (res) => {
            console.log(res);
            const data = res.data as LoginResult;
            token.value = data.token;
            isLogin.value = true;
            await saveStatus();
            init();
            router.push("/home");
        })
    }
    function logout() {
        doLogout().then(() => {
            isLogin.value = false;
            token.value = {} as Token;
            const userStore = useUserStore();
            userStore.user = {} as User;
        });
    }
    async function init() {
        const store = await Store.load("store.auth");
        if (store != null) {
            const get = await store.get("token") as Token;
            if (get != null && typeof get == 'object') {
                token.value = get as Token;
                isLogin.value = true
            } else {
                goLogin();
            }
        } else {
            goLogin();
        }
        if (isLogin.value) {
            const userStore = useUserStore();
            await userStore.doGetUserInfo();
        }
    }
    async function saveStatus() {
        const store = await Store.load("store.auth");
        if (store != null) {
            store.set("token", token.value);
            await store.save();
        }
    }
    function goLogin() {
        router.push("/my/login");
    }
    return {
        token,
        getToken, getIsLogin,
        login, logout, init, goLogin
    }
})